"use client";

import React, { useState, useEffect } from "react";
import { DeleteOutlined } from "@ant-design/icons";
import {
  Form,
  Input,
  Button,
  Typography,
  Space,
  Select,
  Spin,
  Modal,
  Card,
  Pagination,
} from "antd";
import { useRouter } from "next/navigation";
import { useUser } from "../../context/userContext";
import api from "../../utils/api";
import fontStyle from "@/components/Font.module.css";

const { Title } = Typography;
const { Option } = Select;

export default function CreatePostPage() {
  const [modalOpen, setModalOpen] = useState(false);
  const [modalTitle, setModalTitle] = useState("");
  const [modalContent, setModalContent] = useState("");

  const [tags, setTags] = useState<any[]>([]);
  const [selectedTags, setSelectedTags] = useState<string[]>([]);
  const [categories, setCategories] = useState<any[]>([]);
  const [selectedCategory, setSelectedCategory] = useState<string>("");
  const [loading, setLoading] = useState<boolean>(true);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(6);
  const [totalTags, setTotalTags] = useState(0);

  const router = useRouter();
  const { user } = useUser();
  const accessToken = user?.access_token || "";

  useEffect(() => {
    const fetchCategories = async () => {
      try {
        const response = await api.get("/categories/all");
        if (response.status === 200 && Array.isArray(response.data.Reponse)) {
          setCategories(response.data.Reponse);
        } else {
          setCategories([]);
        }
      } catch (error) {
        console.error("获取分区数据失败:", error);
        setCategories([]);
      } finally {
        setLoading(false);
      }
    };
    fetchCategories();
  }, []);

  useEffect(() => {
    const fetchTags = async () => {
      setLoading(true);
      try {
        const response = await api.get("/tags/all", {
          params: {
            page: page.toString(),
            pageSize: pageSize.toString(),
          },
        });

        if (response.status === 200) {
          setTags(response.data.Tags);
          setTotalTags(response.data.total);
        } else {
          setTags([]);
          setTotalTags(0);
        }
      } catch (error) {
        console.error("获取标签数据失败:", error);
        setTags([]);
        setTotalTags(0);
      } finally {
        setLoading(false);
      }
    };

    fetchTags();
  }, [page, pageSize]);

  const handleSubmit = async (values) => {
    try {
      const response = await api.post(
        "/posts/create",
        {
          title: values.title,
          content: values.content,
          categoryId: selectedCategory,
          tags: selectedTags,
        },
        {
          headers: { Authorization: `Bearer ${accessToken}` },
        }
      );

      if (response.data.success === true) {
        setModalTitle("成功");
        setModalContent("帖子创建成功！请耐心等待管理员审核！");
        setModalOpen(true);
      } else {
        setModalTitle("失败");
        setModalContent("创建帖子失败，请重试");
        setModalOpen(true);
      }
    } catch (error) {
      setModalTitle("服务器错误");
      setModalContent("请稍后再试");
      setModalOpen(true);
      console.error(error);
    }
  };

  const handleSelectTag = (tag) => {
    if (!selectedTags.includes(tag.name)) {
      setSelectedTags([...selectedTags, tag.name]); // 保存 tag.name 而不是 tag.id
    }
  };

  const handleRemoveTag = (tagName) => {
    setSelectedTags(selectedTags.filter((name) => name !== tagName));
  };

  const handleBackToHomepage = () => router.push("/homepage/home");

  return (
    <div
      style={{
        minHeight: "100vh",
        padding: "20px",
        background: "linear-gradient(135deg, #F4EDEB 0%, #F0E6E2 100%)",
      }}
    >
      <Modal
        open={modalOpen}
        title={modalTitle}
        onOk={() => {
          setModalOpen(false);
          handleBackToHomepage();
        }}
        onCancel={() => setModalOpen(false)}
        okButtonProps={{ style: { borderRadius: 8 } }}
        cancelButtonProps={{ style: { borderRadius: 8 } }}
      >
        <p>{modalContent}</p>
      </Modal>

      <div
        style={{
          maxWidth: 900,
          margin: "0 auto",
          background: "white",
          borderRadius: 20,
          boxShadow: "0 4px 20px rgba(0,0,0,0.08)",
          padding: 24,
        }}
      >
        <Title level={2} style={{ color: "#7A6E6E" }}>
          发布帖子
        </Title>
        <Form onFinish={handleSubmit} layout="vertical">
          <Form.Item
            label={<span className={fontStyle.text}>标题</span>}
            name="title"
            rules={[{ required: true, message: "请输入标题！" }]}
          >
            <Input size="large" placeholder="请输入标题" />
          </Form.Item>

          <Form.Item
            label={<span className={fontStyle.text}>分区</span>}
            name="category"
            rules={[{ required: true, message: "请选择分区！" }]}
          >
            <Select
              placeholder="请选择分区"
              value={selectedCategory}
              onChange={(value) => setSelectedCategory(value)}
              size="large"
            >
              {categories.map((category) => (
                <Option key={category.id} value={category.id}>
                  {category.name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <div style={{ marginBottom: 16 }}>
            <span className={fontStyle.text}>标签</span>
            <div style={{ marginTop: 8, marginBottom: 12 }}>
              {selectedTags.map((tagName) => (
                <Button
                  key={tagName}
                  onClick={() => handleRemoveTag(tagName)}
                  className="bg-primary/10 text-primary rounded-full px-3 py-1 text-sm flex items-center hover:bg-primary/20 transition-colors"
                >
                  {tagName} <DeleteOutlined className="ml-1" />
                </Button>
              ))}
            </div>

            {loading ? (
              <Spin size="small" />
            ) : (
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "repeat(auto-fill, minmax(240px, 1fr))",
                  gap: 16,
                }}
              >
                {tags.map((tag) => (
                  <div
                    key={tag.id}
                    onClick={() => handleSelectTag(tag)}
                    style={{
                      borderRadius: 10,
                      backgroundColor: "#F4EDEB",
                      padding: "10px 12px",
                      cursor: "pointer",
                      transition: "background-color 0.3s",
                    }}
                    onMouseEnter={(e) =>
                      (e.currentTarget.style.backgroundColor = "#e9dfdd")
                    }
                    onMouseLeave={(e) =>
                      (e.currentTarget.style.backgroundColor = "#F4EDEB")
                    }
                  >
                    <div style={{ color: "#7A6E6E", fontWeight: "bold" }}>
                      {tag.name}
                    </div>
                    <div style={{ color: "#AFAFAF", fontSize: 12 }}>
                      {tag.description}
                    </div>
                  </div>
                ))}
              </div>
            )}

            <div style={{ textAlign: "center", marginTop: 16 }}>
              <Pagination
                current={page}
                pageSize={pageSize}
                total={totalTags}
                onChange={(p, ps) => {
                  setPage(p);
                  setPageSize(ps);
                }}
              />
            </div>
          </div>

          <Form.Item
            label={<span className={fontStyle.text}>内容</span>}
            name="content"
            rules={[{ required: true, message: "请输入内容！" }]}
          >
            <Input.TextArea rows={6} placeholder="请输入内容" />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button
                onClick={handleBackToHomepage}
                style={{
                  backgroundColor: "#eee",
                  color: "#7A6E6E",
                  borderRadius: 20,
                }}
              >
                <div className={fontStyle.text}>返回首页</div>
              </Button>
              <Button
                type="primary"
                htmlType="submit"
                style={{
                  backgroundColor: "#D6A7A1",
                  borderColor: "#D6A7A1",
                  borderRadius: 20,
                }}
              >
                <div className={fontStyle.whitetext}>发布</div>
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
}
